package jp.test;

import org.cybergarage.upnp.Device;
import org.geed.util.UPnPCipher;

public class WorkerThread extends Thread {

	private AClient a = null;
	
	private boolean lockAVReceive = false;
	private boolean avPowerOn = false;
	
	private long startTime = 0;

	public void setA(AClient a) {
		this.a = a;
	}

	public void setStartTime(long startTime) {
		this.startTime = startTime;
	}
	
	public void run(){
		
		try{
			Thread.sleep(startTime);
		}catch(Exception e){}
		
		
		
		int retryCnt = 1;
		
		Device gc = a.chooseGroupController();
		
		String friendlyName = gc.getFriendlyName();
		System.out.println(a.getDeviceName()+" selected GC Friendly "+friendlyName);
		
		a.setGroupControllerDevice(gc);
		
		while( !a.startKPSMode()){
			
			
			System.err.println(getName()+" security start failed "+retryCnt);
			retryCnt++;
			
			try{
				Thread.sleep(1000);
			}catch(Exception e){}
		}
		a.setStatus(AClient.STATUS_REGISTERED);
		
		int replay = 4;
		while(true){
			if(lockAVReceive){
				System.out.println(getName()+" start AVReceive3...");
				a.startAVReceiever(avPowerOn);
				replay --;
				
				if(replay ==0){
					break;
				}
			}
			try{
				Thread.sleep(3000);
			}catch(Exception e){}
		}
		
		
	}
	

	
	public void leaveGroup(){
		if(a.getStatus() == AClient.STATUS_REGISTERED){
			System.err.println(getName()+" leaveGroup...");
			a.leaveGroup();
		}
		
	}
	
	public void securedGetClockTime(){
		long startTime = System.currentTimeMillis();
		a.securedGetClockTime();
		long stopTime = System.currentTimeMillis();
		
		long elapsedTime = stopTime - startTime;
		a.printESPTime(elapsedTime, "time\\securegetclock_test.log", getName());
	}
	
	public void getClockTime(){
		long startTime = System.currentTimeMillis();
		a.getClockTime();
		long stopTime = System.currentTimeMillis();
		
		long elapsedTime = stopTime - startTime;
		a.printESPTime(elapsedTime, "time\\getclock_test500.log", getName());
	}
	
	public void setAVPowerOn(boolean power){
		this.avPowerOn = power;
		this.lockAVReceive = true;
	}

	
	
}
